package com.redispro.service.impl;

import cn.hutool.json.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redispro.entity.ShopType;
import com.redispro.mapper.ShopTypeMapper;
import com.redispro.service.IShopTypeService;
import com.redispro.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李力
 * @since 2022-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<ShopType> queryTypeList() {
        List<String> types = redisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_TYPE, 0, -1);
        List<ShopType> all = new ArrayList<>();
        if (types != null && !types.isEmpty()) {
            types.forEach(type -> {
                ShopType shopType = JSONUtil.toBean(type, ShopType.class);
                all.add(shopType);
            });
            return all;
        }
        LambdaQueryWrapper<ShopType> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(ShopType::getSort);
        List<ShopType> list = list(wrapper);
        if (list != null && !list.isEmpty()) {
            List<String> ty = new ArrayList<>();
            list.forEach(shopType -> {
                String jsonStr = JSONUtil.toJsonStr(shopType);
                ty.add(jsonStr);
            });
            redisTemplate.opsForList().leftPushAll(RedisConstants.CACHE_SHOP_TYPE, ty);
            redisTemplate.expire(RedisConstants.CACHE_SHOP_TYPE, 30, TimeUnit.MINUTES);
        }
        return list;
    }
}
